﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace _5E.Utils.StringHelper.Extension
{
    public static class StringExtension
    {
        static Regex cleanRegEx = new Regex(@"\s+|_|-|\.", RegexOptions.Compiled);

        public static string ToMD5(this string str)
        {
            return str.ToMD5(Encoding.Default);
        }

        public static string ToMD5(this string str, Encoding encoding)
        {
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                byte[] encodingBytes = encoding.GetBytes(str), md5Bytes = md5.ComputeHash(encodingBytes);
                return BitConverter.ToString(md5Bytes);
            }
        }

        public static string ToBCrypt(this string str)
        {
            return BCrypt.HashPassword(str, BCrypt.GenerateSalt());
        }

        public static bool CompareByBCrypt(this string hashed, string plaintext)
        {
            var equal = BCrypt.CheckPassword(plaintext, hashed);
            return equal;
        }

        public static string ToPascalCase(this string str)
        {
            string[] names = cleanRegEx.Split(str);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < names.Length; i++)
            {
                if (string.IsNullOrEmpty(names[i]))
                {
                    result.Append(i == 0 ? "_" : string.Empty);
                    continue;
                }
                result.Append(char.ToUpper(names[i].ToLower()[0]) + names[i].Substring(1));
            }
            return result.ToString();
        }
    }
}
